import { baseUrl } from './constant.js'
import { Dialog } from 'vant';
import cache from '@/utils/cached.js'
import {isObject} from '@/utils/util.js'

// 自定义公共请求头
function getCustomerHeader() {
  return {
    Authorization: 'Bearer ' + cache.getToken()
  };
}

// 处理响应头
function handleResponseHeader(header) {
	console.log(header);
  const token = header && header['access_token'];
  if (token) {
    cache.setToken(token);
  }
}

// 添加签名参数
function addSign(url) {
  const witeList = [];
  const signData = cache.getSignData();
  
  if (!signData) {
    return url;
  }
  
  const lowerUrl = url.toLowerCase();
  const isNeedSign = lowerUrl.indexOf('qu-live-seckill-api') > -1 || lowerUrl.indexOf('qu-live-activity-api') > -1;
  
  if (isNeedSign) {
    return appendParamToUrl(url, signData);
  }
  
  return url;
}

// 将参数添加到URL上
function appendParamToUrl(url, params) {
  if (!params || !Object.keys(params).length) {
    return url;
  }
  
  const queryArr = [];
  for(let [key, value] of Object.entries(params)) {
    queryArr.push(`${key}=${value}`);
  }
  const queryStr = queryArr.join('&');
  url = url + (url.indexOf('?') > -1 ? '&' : '?') + queryStr;
  
  return url;
}

// 请求
function request(options) {
  let {url, method = 'GET', data, params, showLoading = false} = options;
  const customerHeader = getCustomerHeader(url);
  
  // post请求追加params参数到URL上
  if(method.toLowerCase() === 'post') {
    url = appendParamToUrl(url, params);
  } else if(method.toLowerCase() === 'get') {
    // get请求所有参数都会加到url上
    data = {...data, ...params};
  }
  
  // 增加签名参数
  // url = addSign(url);
  return new Promise((resolve, reject) => {
    if (showLoading) {
      uni.showLoading({
        mask: true
      });
    }
    
    const consoleObj = {url, param:data};
    uni.request({
      url: `${baseUrl}${url}`,
      method,
      data,
      header: {...customerHeader},
      success: (res) => {
        console.log(consoleObj.url, consoleObj.param, res.data);
        console.log(res);
				
        let {code, message} = res.data;
        let resData = isObject(res.data) ? res.data.data : res.data;
				
				if(res.statusCode == 500) {
					reject(res.data.error);
					return;
				}
        
        if (+code !== 200) {
          if (+code === '10021') {
            Dialog.alert({
              message: `非法签名参数！\n ${url}`,
            });
          }
          if(+code === 401) {
            Dialog.alert({
              message: `登录失效，请重新登录`,
            })
            .then(()=>{
              uni.navigateTo({
                url: '/pages/login/login'
              })
            })
          }
          reject({message, code, data: resData});
        } else {
          resolve(resData);
        }
      },
      fail: (err) => {
        console.log(`请求错误：${url}`, err);
        reject({
          code: '-1',
          message: '网络连接出错，请重试'
        });
      },
      complete: () => {
        showLoading && uni.hideLoading();
      }
    });
  })
}

// 文件上传
function upload(options) {
  const {url, name = 'file', filePath, data} = options;
  const customerHeader = getCustomerHeader(url);
  
  return new Promise((resolve, reject) => {
    uni.uploadFile({
      url: `${baseUrl}${url}`,
      filePath,
      name,
      formData: {...data},
      header: {...customerHeader},
      success: (res) => {
        let parsedData = res.data;
        try {
          parsedData = JSON.parse(parsedData);
          const {data: resData, code, message} = parsedData;
          if (+code !== 200) {
            reject(message);
          } else {
            resolve(resData);
          }
        } catch (e) {
          reject(e)
        }
      },
      fail: (err) => {
        console.log(`${url}:${err + ''}`);
        reject(err);
      }
    });
  });
}

export { request, upload }